package com.codermn.并发访问控制.锁;

import java.time.LocalDateTime;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author jxau_scf
 * @date 2021/8/13 - 14:47
 */
public class LockDemo {
    private void doSome(ReentrantReadWriteLock.WriteLock writeLock){
        try {
            writeLock.lock();
            System.out.println("持有锁成功 " + Thread.currentThread().getName() + "  >  " + LocalDateTime.now());
            Thread.sleep(2000);
            System.out.println("执行完毕 " + Thread.currentThread().getName() + "  >  " + LocalDateTime.now());
            writeLock.unlock();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void lockTest() throws InterruptedException {
        ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
        new Thread(()->doSome(reentrantReadWriteLock.writeLock())).start();
        new Thread(()->doSome(reentrantReadWriteLock.writeLock())).start();
        new Thread(()->doSome(reentrantReadWriteLock.writeLock())).start();
        new Thread(()->doSome(reentrantReadWriteLock.writeLock())).start();

        Thread.sleep(10000);
    }
}
